package com.easy.sk.controller;

import com.alibaba.fastjson.JSON;
import com.easy.common.service.SKService;
import com.easy.common.util.Result;
import com.easy.common.util.SKRequest;
import com.easy.common.util.SYS;
import com.easy.common.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sk")
public class SKController {
    @Autowired
    SKService skService;
    
    @Autowired
    RedisTemplate redisTemplate;
    
    /**
     * /sk/33/12 33为秒杀活动id  12为商品id(skgoodsid)
     * 秒杀
     * @param activityid 秒杀活动 秒杀活动id
     * @param skgoodsid  秒杀数据 秒杀商品的id
     * @param request   请求对象 获取token  获取userid
     * @return
     */
    @PostMapping("/{activity_id}/{seckill_goods_id}/{delivery_addr_id}")
    public Result sk(@PathVariable("activity_id") Integer activityid,
                     @PathVariable("seckill_goods_id") Integer skgoodsid,
                     @PathVariable("delivery_addr_id") Integer delivery_addr_id,
                     HttpServletRequest request) {
        // 获取登录用户id值
        String token = request.getHeader(SYS.TOKEN_AUTHORIZATION);
        
        // 简单的前置检查
        if (token == null || token.isEmpty() || activityid == null || skgoodsid == null || delivery_addr_id == null) {
            return Result.fail(400, "参数错误");
        }
        
        // 验证token有效性
        if (!TokenUtil.verify(token)) {
            return Result.fail(401, "token无效");
        }
        
        // 从token中解析用户ID
        Integer userid = null;
        try {
            Object userIdObj = TokenUtil.getOption(token, SYS.TOKEN_KEY_ID);
            if (userIdObj != null) {
                userid = Integer.valueOf(userIdObj.toString());
            }
        } catch (Exception e) {
            return Result.fail(401, "无法解析用户信息");
        }
        
        if (userid == null) {
            return Result.fail(401, "用户未登录");
        }
        
        // 防止用户重复提交秒杀请求 (使用Redis实现请求去重)
        String requestKey = "sk_request:" + userid + ":" + skgoodsid;
        if (Boolean.TRUE.equals(redisTemplate.hasKey(requestKey))) {
            return Result.fail(400, "请勿重复提交秒杀请求");
        }
        
        // 设置请求去重标记，有效期10分钟
        redisTemplate.opsForValue().set(requestKey, "1", 10, TimeUnit.MINUTES);
        
        String skid = UUID.randomUUID().toString(); // 可以自定义算法生成秒杀记录id
        SKRequest skRequest = new SKRequest(userid, skgoodsid, activityid, delivery_addr_id, skid);

        // fastJSON将SKRequest转换成JSON字符串,再将消息发送到MQ  交给service发送
        String message = JSON.toJSONString(skRequest);
        skService.sendMSG(message);
        
        // 响应请求(把秒杀记录id传回去了)
        return Result.success(skid);
    }
}
